<?php
/* prestalovecontact.php version 1.1 created by PrestaLove.com */
class prestalovecontact extends Module
{
	private $_html = '';
	
	public function __construct()
	{
		$this->name = 'prestalovecontact';
		$this->tab = 'front_office_features';
		$this->version = 1.1;
		
		parent::__construct();
		
		$this->displayName = $this->l('PrestaLove Ajax Contact Form');
		$this->description = $this->l('PrestaLove Ajax Contact Form.');
	}

	public function install()
	{
		if(!parent::install() ||
		 !$this->registerHook('header'))
			return false;
		return true;
	}

	public function uninstall()
	{
		if(!parent::uninstall())
			return false;
		return true;
	}
	

	public function putContent($xml_data, $key, $field, $forbidden, $section)
	{
		foreach ($forbidden AS $line)
			if ($key == $line)
				return 0;
		
		if (!preg_match('/^'.$section.'_/i', $key))
			return 0;
		$key = preg_replace('/^'.$section.'_/i', '', $key);
		$field = htmlspecialchars($field);
		if (!$field) {
			return 0;
		
		}
		return ("\n".'		<'.$key.'>'.$field.'</'.$key.'>');
	}
	public function getContent()
	{
    	global $cookie;
		$this->_html .= '<h2>'.$this->l('PrestaLove Ajax Contact Form').'</h2>';
        
		if(Tools::isSubmit('submitPrestaLoveContact'))
    	{			
			$errors = '';
			// Forbidden key
			$forbidden = array('submitPrestaLoveContact');
			
			foreach ($_POST AS $key => $value)
				if (!Validate::isCleanHtml($_POST[$key]))
				{
					$this->_html .= $this->displayError($this->l('Invalid html field, javascript is forbidden'));
					$this->_displayForm();
					return $this->_html;
				}

			// Generate new XML data
			$newXml = '<?xml version=\'1.0\' encoding=\'utf-8\' ?>'."\n";
			$newXml .= '<prestalovecontact>'."\n";
			$newXml .= '	<body>';
			// Making body data
			foreach ($_POST AS $key => $field)
				if ($line = $this->putContent($newXml, $key, $field, $forbidden, 'prestalovec'))
					$newXml .= $line;
			
		    $newXml .= "\n".'		<from>'. Configuration::get('PS_SHOP_EMAIL') . '</from>'."\n";
			$newXml .= "\n".'	</body>'."\n";
			$newXml .= '</prestalovecontact>'."\n";

			/* write it into the editorial xml file */
			if ($fd = @fopen(dirname(__FILE__).'/data/prestalovecontact.xml', 'w'))
			{
				if (!@fwrite($fd, $newXml))
					$errors .= $this->displayError($this->l('Unable to write to the prestalovecontact.xml file.'));
				if (!@fclose($fd))
					$errors .= $this->displayError($this->l('Can\'t close the prestalovecontact.xml file.'));
			}
			else
				$errors .= $this->displayError($this->l('Unable to update the prestalovecontact file.<br />Please check the prestalovecontact file\'s writing permissions.'));

			$this->_html .= $errors == '' ? $this->displayConfirmation($this->l('Settings updated successfully')) : $errors;
		}
		
		
		/* display configuration form */
		$this->_displayForm();
		
	    echo $this->_html;	
	}
	private function _displayForm()
	{
		global $cookie;
		
		$this->_html .= '
		  <script type="text/javascript" src="'.__PS_BASE_URI__.'/modules/prestalovecontact/colorpicker/js/jquery1-6.min.js"></script>
		 <script type="text/javascript" src="'.__PS_BASE_URI__.'/modules/prestalovecontact/colorpicker/js/mColorPicker.min.js"></script>
		 <script type="text/javascript" charset="UTF-8">
	  		$(".colorpick").mColorPicker({imageFolder: "'.__PS_BASE_URI__.'/modules/prestalovecontact/colorpicker/images/"})
    	</script>
		';
		/* xml loading */
		$xml = false;
		if (file_exists(dirname(__FILE__).'/data/prestalovecontact.xml'))
				if (!$xml = simplexml_load_file(dirname(__FILE__).'/data/prestalovecontact.xml'))
					$this->_html .= $this->displayError($this->l('Your prestalovecontact.xml file is empty.'));
		
		$this->_html .= '<fieldset style="width: 900px;">
      			<legend><img src="../img/admin/cog.gif" alt="" title="" />'.$this->l('Configuration').'</legend>';
		
		$this->_html .= '<form action="'.$_SERVER['REQUEST_URI'].'" method="post" id="form">';		
		
		$this->_html .= '
				<label>'.$this->l('Recipient:').'</label>
				<div class="margin-form">
					<input type="text" name="prestalovec_recipient" size="64" value="'.($xml ? stripslashes(htmlspecialchars($xml->body->recipient)) : '').'" />
					<p class="clear">'.$this->l('The text display email of Recipient').'</p>
				</div>';
		
		$this->_html .= '<br /><br /><fieldset style="width: 880px;">
      			<legend>'.$this->l('Translate to your language').'</legend>';		
		$this->_html .= '
				<label>'.$this->l('Title: ').'</label>
				<div class="margin-form">
					<input type="text" name="prestalovec_title" size="64" value="'.($xml ? stripslashes(htmlspecialchars($xml->body->title)) : '').'" />
					<p class="clear">'.$this->l('The text display title of contact form').'</p>
				</div>';
				
		$this->_html .= '
				<label>'.$this->l('Name:').'</label>
				<div class="margin-form">
					<input type="text" name="prestalovec_name_label" size="64" value="'.($xml ? stripslashes(htmlspecialchars($xml->body->name_label)) : '').'" />
					<p class="clear">'.$this->l('Requite field').'</p>
				</div>';
				
		$this->_html .= '
				<label>'.$this->l('Email:').'</label>
				<div class="margin-form">
					<input type="text" name="prestalovec_email_label" size="64" value="'.($xml ? stripslashes(htmlspecialchars($xml->body->email_label)) : '').'" />
					<p class="clear">'.$this->l('Requite field').'</p>
				</div>';
				
		$this->_html .= '
				<label>'.$this->l('Subject:').'</label>
				<div class="margin-form">
					<input type="text" name="prestalovec_subject_label" size="64" value="'.($xml ? stripslashes(htmlspecialchars($xml->body->subject_label)) : '').'" />
				</div>';
				
		$this->_html .= '
				<label>'.$this->l('Message:').'</label>
				<div class="margin-form">
					<input type="text" name="prestalovec_message_label" size="64" value="'.($xml ? stripslashes(htmlspecialchars($xml->body->message_label)) : '').'" />
					<p class="clear">'.$this->l('Requite field').'</p>
				</div>';
				
		$this->_html .= '
				<label>'.$this->l('Send me a copy:').'</label>
				<div class="margin-form">
					<input type="text" name="prestalovec_send_me_copy" size="64" value="'.($xml ? stripslashes(htmlspecialchars($xml->body->send_me_copy)) : '').'" />
				</div>';
				
		$this->_html .= '
				<label>'.$this->l('Send:').'</label>
				<div class="margin-form">
					<input type="text" name="prestalovec_send_text" size="64" value="'.($xml ? stripslashes(htmlspecialchars($xml->body->send_text)) : '').'" />
				</div>';
				
		$this->_html .= '
				<label>'.$this->l('Cancel:').'</label>
				<div class="margin-form">
					<input type="text" name="prestalovec_cancel_text" size="64" value="'.($xml ? stripslashes(htmlspecialchars($xml->body->cancel_text)) : '').'" />
				</div>';
		$this->_html .= '</fieldset><br /><br />';
		
		$this->_html .= '<fieldset style="width: 880px;">
      			<legend>'.$this->l('CSS configuration').'</legend>';
		$this->_html .= '
				<label>'.$this->l('Background color').'</label>
				<div class="margin-form">
					<input class="colorpick" type="color" data-hex="true" name="prestalovec_background_color" size="10" value="'.($xml ? stripslashes(htmlspecialchars($xml->body->background_color)) : '#333').'" />
					<p class="clear">'.$this->l('The text display background color').'</p>
				</div>';
		
		$this->_html .= '
				<label>'.$this->l('Title color').'</label>
				<div class="margin-form">
					<input class="colorpick" type="color" data-hex="true" name="prestalovec_title_color" size="10" value="'.($xml ? stripslashes(htmlspecialchars($xml->body->title_color)) : '#d90e20').'" />
					<p class="clear">'.$this->l('The text display color of title/links').'</p>
				</div>';	
		
		$this->_html .= '
				<label>'.$this->l('Text color').'</label>
				<div class="margin-form">
					<input class="colorpick" type="color" data-hex="true" name="prestalovec_text_color" size="10" value="'.($xml ? stripslashes(htmlspecialchars($xml->body->text_color)) : '#EEE').'" />
					<p class="clear">'.$this->l('The text display color of text').'</p>
				</div>';	
		
		$this->_html .= '
				<label>'.$this->l('Input background color').'</label>
				<div class="margin-form">
					<input class="colorpick" type="color" data-hex="true" name="prestalovec_input_bg_color" size="10" value="'.($xml ? stripslashes(htmlspecialchars($xml->body->input_bg_color)) : '#EEE').'" />
					<p class="clear">'.$this->l('The text display background color of input box').'</p>
				</div>';	
		
		$this->_html .= '
				<label>'.$this->l('Input border color').'</label>
				<div class="margin-form">
					<input class="colorpick" type="color" data-hex="true" name="prestalovec_input_border_color" size="10" value="'.($xml ? stripslashes(htmlspecialchars($xml->body->input_border_color)) : '#FFF').'" />
					<p class="clear">'.$this->l('The text display border color of input box').'</p>
				</div>';		
		
		$this->_html .= '
				<label>'.$this->l('Button background color').'</label>
				<div class="margin-form">
					<input class="colorpick" type="color" data-hex="true" name="prestalovec_button_bg_color" size="10" value="'.($xml ? stripslashes(htmlspecialchars($xml->body->button_bg_color)) : '#D90E20').'" />
					<p class="clear">'.$this->l('The text display background color of button').'</p>
				</div>';			
		
		$this->_html .= '
				<label>'.$this->l('Button color').'</label>
				<div class="margin-form">
					<input class="colorpick" type="color" data-hex="true" name="prestalovec_button_color" size="10" value="'.($xml ? stripslashes(htmlspecialchars($xml->body->button_color)) : '#FFF').'" />
					<p class="clear">'.$this->l('The text display color of button').'</p>
				</div>';	
		
		$this->_html .= '
				<label>'.$this->l('Button hover color').'</label>
				<div class="margin-form">
					<input class="colorpick" type="color" data-hex="true" name="prestalovec_button_hover_color" size="10" value="'.($xml ? stripslashes(htmlspecialchars($xml->body->button_hover_color)) : '#f49000').'" />
					<p class="clear">'.$this->l('The text display background color of button when hover').'</p>
				</div>';
		$this->_html .= '</fieldset>';
		
		$this->_html .= '
				<div class="clear pspace"></div>
				<div class="margin-form clear"><input type="submit" name="submitPrestaLoveContact" value="'.$this->l('  Save  ').'" class="button" /></div>
			</form>
		</fieldset>';
	}
	
	public function hookHeader($params)
	{
		global $smarty;
		
		$css_text = '<style type="text/css"> ';
		if (file_exists(dirname(__FILE__).'/data/prestalovecontact.xml'))
		{
			if ($xml = simplexml_load_file(dirname(__FILE__).'/data/prestalovecontact.xml'))
			{
				$background_color   = $xml->body->background_color;
				$title_color        = $xml->body->title_color;
				$text_color         = $xml->body->text_color;
				$input_bg_color     = $xml->body->input_bg_color;
				$input_border_color = $xml->body->input_border_color;
				$button_bg_color    = $xml->body->button_bg_color;
				$button_color       = $xml->body->button_color;
				$button_hover_color = $xml->body->button_hover_color;
				
				$css_text .= ' #simplemodal-data {background:'.$background_color.'; color:'.$text_color.';} ';
				$css_text .= ' #prestalovecontact-container h1 {color:'.$title_color.'} ';
				$css_text .= ' #prestalovecontact-container .prestalovecontact-error {border: 2px solid '.$title_color.';} ';
				$css_text .= ' #prestalovecontact-container .prestalovecontact-input {background:'.$input_bg_color.'; border:1px solid '.$input_border_color.';} ';
				$css_text .= ' #prestalovecontact-container .prestalovecontact-button {background:'.$button_bg_color.'; color:'.$button_color.';}';
				$css_text .= ' #prestalovecontact-container .prestalovecontact-button:hover {background:'.$button_hover_color.';}';
				$css_text .= ' #prestalovecontact-container a.modal-close, #prestalovecontact-container a.modal-close:link, #prestalovecontact-container a.modal-close:active, #prestalovecontact-container a.modal-close:visited {color:'.$title_color.'}';
				$css_text .= ' #prestalovecontact-container a.modal-close:hover {color:'.$text_color.'}';
			}
		}
		
		$css_text .= ' </style>';
		
		$javascript_text = "<script type=\"text/javascript\">
		jQuery(function ($) {
			var prestalovecontact = {
			message: null,
			init: function () {
				$('#header_link_contact a, a.prestalovecontact').click(function (e) {
					e.preventDefault();
					// load the contact form using ajax
					var prestalovecontact_file = '"._MODULE_DIR_."prestalovecontact/data/prestalovecontact.php';
					
					$.get(prestalovecontact_file, function(data){
												 
						// create a modal dialog with the data
						$(data).modal({
							closeHTML: '<a href=\"#\" title=\"Close\" class=\"modal-close\">x</a>',
							position: [\"15%\",],
							overlayId: 'prestalovecontact-overlay',
							containerId: 'prestalovecontact-container',
							onOpen: prestalovecontact.open,
							onShow: prestalovecontact.show,
							onClose: prestalovecontact.close
						});
					});
				});
			},
			open: function (dialog) {
				
				// input field font size
				if ($.browser.safari) {
					$('#prestalovecontact-container .prestalovecontact-input').css({
						'font-size': '.9em'
					});
				}
	
				// dynamically determine height
				var h = 280;
				if ($('#prestalovecontact-subject').length) {
					h += 26;
				}
				if ($('#prestalovecontact-cc').length) {
					h += 22;
				}
	
				var title = $('#prestalovecontact-container .prestalovecontact-title').html();
				$('#prestalovecontact-container .prestalovecontact-title').html('Loading...');
				dialog.overlay.fadeIn(200, function () {
					dialog.container.fadeIn(200, function () {
						dialog.data.fadeIn(200, function () {
							$('#prestalovecontact-container .prestalovecontact-content').animate({
								height: h
							}, function () {
								$('#prestalovecontact-container .prestalovecontact-title').html(title);
								$('#prestalovecontact-container form').fadeIn(200, function () {
									$('#prestalovecontact-container #prestalovecontact-name').focus();
	
									$('#prestalovecontact-container .prestalovecontact-cc').click(function () {
										var cc = $('#prestalovecontact-container #prestalovecontact-cc');
										cc.is(':checked') ? cc.attr('checked', '') : cc.attr('checked', 'checked');
									});
	
									// fix png's for IE 6
									if ($.browser.msie && $.browser.version < 7) {
										$('#prestalovecontact-container .prestalovecontact-button').each(function () {
											if ($(this).css('backgroundImage').match(/^url[(\"']+(.*\.png)[)\"']+$/i)) {
												var src = RegExp.$1;
												$(this).css({
													backgroundImage: 'none',
													filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\"' +  src + '\", sizingMethod=\"crop\")'
												});
											}
										});
									}
								});
							});
						});
					});
				});
			},
			show: function (dialog) {
				$('#prestalovecontact-container .prestalovecontact-send').click(function (e) {
					e.preventDefault();
					// validate form
					if (prestalovecontact.validate()) {
						var msg = $('#prestalovecontact-container .prestalovecontact-message');
						msg.fadeOut(function () {
							msg.removeClass('prestalovecontact-error').empty();
						});
						$('#prestalovecontact-container .prestalovecontact-title').html('".$this->l('Sending...')."');
						$('#prestalovecontact-container form').fadeOut(200);
						$('#prestalovecontact-container .prestalovecontact-content').animate({
							height: '80px'
						}, function () {
							$('#prestalovecontact-container .prestalovecontact-loading').fadeIn(200, function () {
								$.ajax({
									url: '"._MODULE_DIR_."prestalovecontact/data/prestalovecontact.php',
									data: $('#prestalovecontact-container form').serialize() + '&action=send',
									type: 'post',
									cache: false,
									dataType: 'html',
									success: function (data) {
										$('#prestalovecontact-container .prestalovecontact-loading').fadeOut(200, function () {
											$('#prestalovecontact-container .prestalovecontact-title').html('".$this->l('Thank you!')."');
											msg.html(data).fadeIn(200);
										});
									},
									error: prestalovecontact.error
								});
							});
						});
					}
					else {
						if ($('#prestalovecontact-container .prestalovecontact-message:visible').length > 0) {
							var msg = $('#prestalovecontact-container .prestalovecontact-message div');
							msg.fadeOut(200, function () {
								msg.empty();
								prestalovecontact.showError();
								msg.fadeIn(200);
							});
						}
						else {
							$('#prestalovecontact-container .prestalovecontact-message').animate({
								height: '30px'
							}, prestalovecontact.showError);
						}
						
					}
				});
			},
			close: function (dialog) {
				$('#prestalovecontact-container .prestalovecontact-message').fadeOut();
				$('#prestalovecontact-container .prestalovecontact-title').html('".$this->l('Goodbye!')."');
				$('#prestalovecontact-container form').fadeOut(200);
				$('#prestalovecontact-container .prestalovecontact-content').animate({
					height: 40
				}, function () {
					dialog.data.fadeOut(200, function () {
						dialog.container.fadeOut(200, function () {
							dialog.overlay.fadeOut(200, function () {
								$.modal.close();
							});
						});
					});
				});
			},
			error: function (xhr) {
				alert(xhr.statusText);
			},
			validate: function () {
				prestalovecontact.message = '';
				if (!$('#prestalovecontact-container #prestalovecontact-name').val()) {
					prestalovecontact.message += '".$this->l('Name is required.')." ';
				}
	
				var email = $('#prestalovecontact-container #prestalovecontact-email').val();
				if (!email) {
					prestalovecontact.message += '".$this->l('Email is required.')." ';
				}
				else {
					if (!prestalovecontact.validateEmail(email)) {
						prestalovecontact.message += '".$this->l('Email is invalid.')." ';
					}
				}
	
				if (!$('#prestalovecontact-container #prestalovecontact-message').val()) {
					prestalovecontact.message += '".$this->l('Message is required.')."';
				}
	
				if (prestalovecontact.message.length > 0) {
					return false;
				}
				else {
					return true;
				}
			},
			validateEmail: function (email) {
				var at = email.lastIndexOf(\"@\");
	
				// Make sure the at (@) sybmol exists and  
				// it is not the first or last character
				if (at < 1 || (at + 1) === email.length)
					return false;
	
				// Make sure there aren't multiple periods together
				if (/(\.{2,})/.test(email))
					return false;
	
				// Break up the local and domain portions
				var local = email.substring(0, at);
				var domain = email.substring(at + 1);
	
				// Check lengths
				if (local.length < 1 || local.length > 64 || domain.length < 4 || domain.length > 255)
					return false;
	
				// Make sure local and domain don't start with or end with a period
				if (/(^\.|\.$)/.test(local) || /(^\.|\.$)/.test(domain))
					return false;
	
				// Check for quoted-string addresses
				// Since almost anything is allowed in a quoted-string address,
				// we're just going to let them go through
				if (!/^\"(.+)\"$/.test(local)) {
					// It's a dot-string address...check for valid characters
					if (!/^[-a-zA-Z0-9!#$%*\/?|^{}`~&'+=_\.]*$/.test(local))
						return false;
				}
	
				// Make sure domain contains only valid characters and at least one period
				if (!/^[-a-zA-Z0-9\.]*$/.test(domain) || domain.indexOf(\".\") === -1)
					return false;	
	
				return true;
				},
				showError: function () {
					$('#prestalovecontact-container .prestalovecontact-message')
						.html($('<div class=\"prestalovecontact-error\"></div>').append(prestalovecontact.message))
						.fadeIn(200);
				}
			};
		
			prestalovecontact.init();
	
		});
		</script>
		
		";
		
		$smarty->assign(array(
			'css_text' => $css_text,
			'javascript_text' => $javascript_text,
		));
		return $this->display(__FILE__, 'prestalovecontact-header.tpl');
	}
}
?>